import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:stock_check/common/dao/WorksDao.dart';
import 'package:stock_check/common/model/ITAsset.dart';
import 'package:stock_check/common/model/assetItemInfo.dart';
import 'package:stock_check/common/model/institutionAsset.dart';
import 'package:stock_check/common/redux/reduxStore.dart';
import 'package:stock_check/common/utils/CommonUtils.dart';
import 'package:stock_check/widget/CommonsWidget.dart';
import 'package:stock_check/widget/FullScreenImage.dart';
import 'package:stock_check/widget/MyScaffold.dart';
import 'package:image_picker/image_picker.dart';

/// 巡检资产清单页
class AssetCheckListPage extends StatefulWidget {
  final dynamic item;
  final String type;
  final int recordId;
  const AssetCheckListPage({Key key, this.item, this.type, this.recordId}) : super(key: key);

  @override
  _AssetCheckListPageState createState() => _AssetCheckListPageState();
}

class _AssetCheckListPageState extends State<AssetCheckListPage> {
  ITAsset itAsset;
  InstitutionAsset institutionAsset;
  bool haveSave = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.type == 'IT类') {
      itAsset = widget.item;
    } else {
      institutionAsset = widget.item;
    }
  }

  @override
  Widget build(BuildContext context) {
    return StoreBuilder<StockState>(builder: (context, store) {
      return MyScaffold(
        title: Text('巡检详细'),
        store: store,
        child:  WillPopScope(
          onWillPop: _saveUpate,
          child:Container(
              child: Column(
                children: <Widget>[
                  _renderHead(),
                  Expanded(
                    child: _renderList(),
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(vertical: 30.0,horizontal: 10.0),
                    child:OutlineButton(
                      child:Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Icon(Icons.save,color: Colors.blue,size: 30.0,),
                          Padding(padding: EdgeInsets.all(2.0)),
                          Text("保存",style: TextStyle(
                              color: Colors.blue,fontWeight: FontWeight.bold,fontSize: 18.0
                          ),)
                        ],
                      ),
                      padding: EdgeInsets.all(10.0),
                      borderSide: BorderSide(
                          color: Colors.blue,
                          width: 2.0
                      ),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
                      onPressed: ()async{
                        CommonsWidget.showLoadingDialog(context, '信息保存中...');
                        if(widget.type == 'IT类'){
                          await WorksDao.saveITAssetInfo(itAsset,widget.recordId);
                        }else{
                          await WorksDao.saveInstitutionAssetInfo(institutionAsset, widget.recordId);
                        }
                        Future.delayed(Duration(seconds: 1),(){
                          Navigator.of(context,rootNavigator: true).pop(context);
                          Navigator.pop(context);
                        });
                      },
                      textColor: Colors.white,
                    ),
                  )
                ],
              ),
            ),
          ));
        });
  }

  // 渲染解释说明
  Widget _renderTextInput(AssetItemInfo item){
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Text(
          '解释说明 : ',
          style: TextStyle(color: Colors.grey, fontSize: 16.0),
        ),
        Expanded(
          child: TextField(
            controller: TextEditingController.fromValue(
                TextEditingValue(
                  // 设置内容
                    text: item.explain,
                    // 保持光标在最后
                    selection: TextSelection.fromPosition(
                        TextPosition(
                            affinity: TextAffinity.downstream,
                            offset: item.explain.length)))),
            decoration: InputDecoration(border: OutlineInputBorder()),
            maxLines: 3,
            onChanged: (value) {
              value = value;
              item.explain = value;
            },
          ),
        )
      ],
    );
  }

  // 渲染下拉菜单
  Widget _renderSelectInput(AssetItemInfo item){
    return Container(
      padding: EdgeInsets.only(top: 12.0),
        child: Column(
          children: <Widget>[
            Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Column(mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    Text('${item.itemContent}: ', style: TextStyle(color: Colors.grey[600], fontSize: 16.0),),
                  ],
                ),
                DropdownButton(
                  isDense: true,
                    value: item.explain,
                    hint: new Text('请选择'),
                    items: item.chooseList.map((m){
                      return new DropdownMenuItem(
                          child: Text(m), value: m
                      );
                    }).toList(),
                    onChanged: (value) {
                      setState(() {
                        item.explain = value;
                      });
                    })
              ],
            ),

          ],
        ));
  }

  // 渲染列表项
  _renderItem(item) {
    Widget render;
    // 如果是ifChoose = 1 代表有选择框
    if(item.ifChoose == 1){
      if(item.chooseList.length>0){
        if(!item.chooseList.contains(item.explain)){
          item.explain = item.chooseList[0];
        }
        render = _renderSelectInput(item);
      }else{
        render = _renderTextInput(item);
      }
    }else{
      render = _renderTextInput(item);
    }
    return Container(
        width: double.infinity,
        padding: EdgeInsets.all(12.0),
        margin: EdgeInsets.all(2.0),
        decoration: BoxDecoration(
            color: Colors.transparent,
            borderRadius: BorderRadius.circular(8.0),
            border: Border.all(
              color: Theme.of(context).primaryColor,
              width: 2.0
            )
        ),
        child: Column(children: <Widget>[
          Row(
//            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(
                width: CommonUtils.getScreenWidth(context)/2,
                child:Text('${item.itemContent}',
                  overflow: TextOverflow.ellipsis,
                  maxLines: 99,
                  style: TextStyle(
                    color: Colors.blue,
                    fontSize: 17.0,
                    fontWeight: FontWeight.bold,
                  ),),
              ),
              Row(
                children: <Widget>[
                  Radio(
                      value: 1,
                      groupValue: item.status,
                      onChanged: (value) {
                        setState(() {
                          item.status = 1;
                        });
                      }),
                  Text('正常', style: TextStyle(
                      color: item.status == 1 ? Colors.blue : Theme.of(context).accentColor),
                  ),
                  Radio(
                      value: 2,
                      groupValue: item.status,
                      activeColor: Colors.amber,
                      onChanged: (value) {
                        setState(() {
                          item.status = 2;
                        });
                      }),

                  Text('异常', style: TextStyle(
                        color: item.status == 2 ? Colors.amber : Theme.of(context).accentColor),
                  ),
                ],
              ),
            ],
          ),
          (item.status==2)?Divider():Container(),
          Offstage(
            offstage: item.status == 1||item.status==0,
            child:Column(
              children: <Widget>[
                render,
                Padding(padding: EdgeInsets.all(10.0),),
                Divider(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: item.pic.length>0?item.pic.split("|").map<Widget>((base64){
                          if(base64.isNotEmpty)
                            return _renderImageStack(item,base64);
                          else
                            return Container();
                        }).toList():<Widget>[],
                      ),
                    ),
                    GestureDetector(
                      onTap: ()=>getImage(item),
                      child:  Column(
                        children: <Widget>[
                          Image(
                            image: AssetImage("images/add_image.png",),
                            width: CommonUtils.getScreenWidth(context)/8,
                          ),
                          Text('拍照上传',style: TextStyle(
                              color: Colors.grey
                          ),)
                        ],
                      ),
                    )
                  ],
                )
              ],
            )
          )
        ]));
  }

  Widget _renderImageStack(AssetItemInfo item,String base64){
    return Container(
      margin: EdgeInsets.only(left: 5.0),
      child: Stack(
        alignment: Alignment.topRight,
        children: <Widget>[
          Align(
            alignment: Alignment.center,
            child: GestureDetector(
              onTap: (){
                showDialog<Null>(
                    context: context, //BuildContext对象
                    barrierDismissible: false,
                    builder: (BuildContext context) {
                      return ShowFullImage( //调用对话框
                        base64:base64,
                      );
                    });
              },
              child: Image.memory(
                Base64Decoder().convert(base64),
                fit:BoxFit.fill,
                width: 180/4,
                height: 360/4,
              ),
            )
          ),
          Positioned(
            top: -15,
            right: -15,
            child: IconButton(icon: Icon(Icons.close,color: Colors.redAccent), onPressed: (){
              List<String> list = item.pic.split('|');
              if(list.length>0){
                list.removeLast();
                list.remove(base64);
                setState(() {
                  item.pic = list.join('|');
                });
              }
            }),
          )
        ],
      ),
    );
  }


  // 拍照上传
  Future getImage(AssetItemInfo item) async {
    if(item.pic.split('|').length-1==2){
      Fluttertoast.showToast(msg: '最多上传两张图片！',gravity: ToastGravity.CENTER);
      return;
    }
    File image = await ImagePicker.pickImage(source: ImageSource.camera,maxWidth: 180,maxHeight: 360);
    String base64;
    setState(() {
      if(image!=null) {
        base64 = Base64Encoder().convert(image.readAsBytesSync());
        setState(() {
          item.pic += base64+"|";
        });
      }
    });
  }

  _renderList() {
    if (widget.type == 'IT类') {
      return ListView.builder(
          itemCount: itAsset.itemList.length,
          itemBuilder: (context, index) {
            return Column(
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                _renderItem(itAsset.itemList[index]),
                Padding(padding: EdgeInsets.all(1.0))
              ],
            );
          });
    } else {
      return ListView.builder(
          itemCount:institutionAsset.itemList.length,
          itemBuilder: (context, index) {
            return Column(
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                _renderItem(institutionAsset.itemList[index]),
                Padding(padding: EdgeInsets.all(1.0))
              ],
            );
          });
    }
  }

  _renderHead() {
    dynamic item = widget.type == 'IT类' ? itAsset : institutionAsset;
    return Card(
      shape: RoundedRectangleBorder(),
      margin: EdgeInsets.zero,
      child: ListTile(
          leading: Row(
        children: <Widget>[
          Icon(Icons.tab,color: Theme.of(context).accentColor,),
          Padding(
            padding: EdgeInsets.only(left: 5.0),
          ),
          Text('${item.name}',style: TextStyle(
            fontSize: 18.0,
            color: Theme.of(context).accentColor,
            fontWeight: FontWeight.bold
          ),),
        ],
      )),
    );
  }

  Future<bool> _saveUpate() async{
    Fluttertoast.showToast(msg: '请点击保存按钮返回页面！');
    return false;
  }
}
